package com.seaside.park.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seaside.common.bean.Result;
import com.seaside.park.bean.CarReception;
import com.seaside.park.bean.CarReceptionLocker;
import com.seaside.park.bean.ParkPlaceResult;
import com.seaside.park.mapper.CarReceptionMapper;
import com.seaside.park.mapper.ParkLockerMapper;
import com.seaside.park.service.CarReceptionService;
import com.seaside.park.service.WebSocketService;
import com.seaside.parkCommon.bean.User;
import com.seaside.parkCommon.mapper.UserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

@Api(tags = "车辆接车信息管理")
@RestController
@RequestMapping("/api/car-reception")
public class CarReceptionApi {

    @Autowired
    private CarReceptionMapper carReceptionMapper;

    @Autowired
    public CarReceptionService carReceptionService;

    @Autowired
    public ParkLockerMapper parkLockerMapper;

    @Autowired
    public UserMapper userMapper;

    @Autowired
    public RestTemplate restTemplate;

    @Autowired
    WebSocketService webSocketService;

    @ApiOperation(value = "查询指定状态的接车信息", response = Result.class)
    @GetMapping("/listAll")
    public Result<List<CarReceptionLocker>> list(@RequestParam(value = "curPage", defaultValue = "1") Integer curPage,
                                                 @RequestParam (value = "curSize", defaultValue = "10") Integer curSize) {
        Page<CarReceptionLocker> page = new Page<>(curPage, curSize);
        IPage<CarReceptionLocker> iPage = carReceptionMapper.selectPageWithParkLocker(page, new QueryWrapper<CarReception>());
        return (Result<List<CarReceptionLocker>>) Result.OK("查询成功", iPage);
    }

    @ApiOperation(value = "查询指定状态的接车信息", response = Result.class)
    @GetMapping("/listByCarStatus")
    public Result<List<CarReceptionLocker>> listByCarStatus(@RequestParam(value = "curPage", defaultValue = "1") Integer curPage,
                                                 @RequestParam(value = "curSize", defaultValue = "10") Integer curSize,
                                                 @RequestParam String carStatus,
                                                 @RequestParam(defaultValue = "") String licence) {
        Page<CarReceptionLocker> page = new Page<>(curPage, curSize);
        QueryWrapper<CarReception> wrapper = new QueryWrapper<>();
        // 支持车牌条件（模糊）
        if(!Objects.equals(licence, "")){
            wrapper.like("cr.licence", licence);
        }
        IPage<CarReceptionLocker> iPage = carReceptionMapper.selectPageWithParkLocker(page, wrapper
                .eq("cr.car_status", carStatus)
                .orderByDesc("cr.updated_at", "id"));
        return (Result<List<CarReceptionLocker>>) Result.OK("查询成功", iPage);
    }

    @ApiOperation(value = "查询指定状态/号码的接车信息", response = Result.class)
    @GetMapping("/listByCarStatusByPhone")
    public Result<List<CarReceptionLocker>> list(@RequestParam(value = "curPage", defaultValue = "1") Integer curPage,
                                                 @RequestParam (value = "curSize", defaultValue = "10") Integer curSize,
                                                 @RequestParam String carStatus,
                                                 @RequestParam String phone) {
        Page<CarReceptionLocker> page = new Page<>(curPage, curSize);
        String[] ss = carStatus.split("/");
        IPage<CarReceptionLocker> iPage = carReceptionMapper.selectPageWithParkLocker(page, new QueryWrapper<CarReception>()
                .in("cr.car_status", ss)
                .eq("cr.phone", phone)
                .orderByDesc("cr.updated_at", "id"));
        return (Result<List<CarReceptionLocker>>) Result.OK("查询成功", iPage);
    }

    @ApiOperation(value = "根据ID查看车辆接车信息", response = Result.class)
    @ApiImplicitParam(paramType = "query", name = "id", dataType = "int", required = true, value = "车辆接车信息编号")
    @GetMapping("/info")
    public Result<CarReception> info(@RequestParam Integer id) {
        CarReception carReception = carReceptionMapper.selectById(id);
        Result<CarReception> result = Result.OK("查询成功");
        result.setData(carReception);
        return result;
    }

    @ApiOperation(value = "查看当前手机号是否注册", response = Result.class)
    @ApiImplicitParam(paramType = "query", name = "phone", dataType = "String", required = true, value = "手机号是否注册")
    @GetMapping("/isRegistered")
    public Result isRegistered(@RequestParam String phone) {
        List<User> users = userMapper.selectList(new QueryWrapper<User>().eq("user_tel", phone));
        if(users != null && users.size() > 0 && !Objects.equals(users.get(0).getUserGuid(), "")){
            return Result.OK("当前手机号已注册", true);
        }
        return Result.OK("当前手机号未注册", false);
    }

    @ApiOperation(value = "根据车牌号查看车辆接车信息", response = Result.class)
    @ApiImplicitParam(paramType = "query", name = "licence", dataType = "String", required = true, value = "车牌号")
    @GetMapping("/info-by-licence")
    public Result<CarReception> infoByLicence(@RequestParam String licence) {
        QueryWrapper<CarReception> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("licence", licence).orderByDesc("id");
        CarReception carReception = carReceptionMapper.selectList(queryWrapper).stream().findFirst().orElse(null);

        if (carReception != null) {
            return Result.OK("查询成功", carReception);
        } else {
            return Result.Error("未找到对应车辆接车信息");
        }
    }

    @ApiOperation(value = "保存车辆接车信息", response = Result.class)
    @PostMapping("/save")
    public Result save(
            @RequestParam("licence") String licence,
            @RequestParam("phone") String phone,
            @RequestParam("name") String name,
            @RequestParam("specialNotes") String specialNotes,
            @RequestParam("specialPhoto") String specialPhoto
    ) {
        String url = "https://mobile.aowo.vip/park/api/status/getParkPlaceTo?zoneId=7";
        String parkNo = "";
        try {
            ResponseEntity<ParkPlaceResult> response = restTemplate.exchange(
                    url, HttpMethod.GET, HttpEntity.EMPTY, ParkPlaceResult.class
            );
            ParkPlaceResult result = response.getBody();
            // 从 Result 对象中直接获取 parkNo
            if (result != null && result.getData() != null) {
               parkNo = result.getData().getParkNo();
            } else {
                return Result.Error("车位信息获取失败");
            }
        } catch (Exception e) {
            return Result.Error( "车位信息获取失败:"+e.getMessage());
        }
        // 创建 CarReception 对象并设置属性
        CarReception carReception = new CarReception();
        carReception.setPosition(parkNo);
        carReception.setLicence(licence);
        carReception.setPhone(phone);
        carReception.setName(name);
        carReception.setSpecialNotes(specialNotes);
        carReception.setSpecialPhoto(specialPhoto);
        carReception.setCreatedAt(LocalDateTime.now());
        carReception.setUpdatedAt(LocalDateTime.now());
        // 创建接车单之后，车辆状态自动变为"已接车"
        carReception.setCarStatus("已接车");

        if (carReception.getId() == 0) {
            carReceptionMapper.insert(carReception);
        } else {
            carReceptionMapper.updateById(carReception);
        }

        return Result.OK("保存成功！", carReception);
    }

    @ApiOperation(value = "删除车辆接车信息", response = Result.class)
    @ApiImplicitParam(paramType = "query", name = "id", dataType = "int", required = true, value = "车辆接车信息编号")
    @PostMapping("/delete")
    public Result<String> delete(@RequestParam Integer id) {
        carReceptionMapper.deleteById(id);
        return Result.OK("删除成功！");
    }

    @ApiOperation(value = "更新车辆接车信息的锁定状态", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", dataType = "int", required = true, value = "车辆接车信息编号"),
            @ApiImplicitParam(paramType = "query", name = "lock_status", dataType = "String", required = true, value = "锁定状态")
    })
    @PostMapping("/update-lock-status")
    public Result<String> updateLockStatus(@RequestParam int id, @RequestParam String lockStatus) {
        carReceptionService.updateLockStatus(id, lockStatus);
        return Result.OK("锁定状态更新成功！");
    }

    @ApiOperation(value = "更新车辆的归还状态", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", dataType = "int", required = true, value = "车辆接车信息编号"),
            @ApiImplicitParam(paramType = "query", name = "return_status", dataType = "String", required = true, value = "归还状态")
    })
    @PostMapping("/returnCar")
    public Result<String> returnCar(@RequestParam int carReceptionId) {
        carReceptionService.returnCar(carReceptionId);
        return Result.OK("锁定状态更新成功！");
    }

    @ApiOperation(value = "更新车辆状态", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", dataType = "int", required = true, value = "车辆接车信息编号"),
            @ApiImplicitParam(paramType = "query", name = "car_status", dataType = "String", required = true, value = "车辆状态")
    })
    @PostMapping("/update-car-status")
    public Result<String> updateCarStatus(@RequestParam int id, @RequestParam String carStatus) {
        carReceptionService.updateCarStatus(id, carStatus);
        return Result.OK("车辆状态更新成功！");
    }

    @ApiOperation(value = "挪车（更改position）", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", dataType = "int", required = true, value = "车辆接车信息编号"),
            @ApiImplicitParam(paramType = "query", name = "movedPhoto", dataType = "String", required = true, value = "挪车照片URL")
    })
    @PostMapping("/moveCar")
    public Result<String> moveCar(@RequestParam int id, @RequestParam String movedPhoto, @RequestParam String position, @RequestParam(defaultValue = "") String movedNotes) {
        carReceptionService.moveCar(id, movedPhoto, position, movedNotes);
        return Result.OK("挪车成功");
    }

    @ApiOperation(value = "挪车前置开锁（开锁）", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", dataType = "int", required = true, value = "车辆接车信息编号"),
            @ApiImplicitParam(paramType = "query", name = "movedPhoto", dataType = "String", required = true, value = "挪车照片URL")
    })
    @PostMapping("/beforeMoveCar")
    public Result<String> beforeMoveCar(@RequestParam String cellId, @RequestParam String carReceptionId) {
        // 传递柜子id开启格子
        String url = "http://175.178.225.26:1685/openCell?cellId=" + cellId;
        try {
            ResponseEntity<Result> response = restTemplate.exchange(
                    url, HttpMethod.POST, HttpEntity.EMPTY, Result.class
            );
            Result result = response.getBody();
            // 开柜成功后修改车辆、钥匙状态
            if (result != null && result.isSucess()) {
                CarReception carReception = carReceptionMapper.selectOne(new QueryWrapper<CarReception>()
                        .eq("id", carReceptionId));
                carReceptionService.updateLockStatus(carReception.getId(), "已出柜");
                carReceptionService.updateCarStatus(carReception.getId(), "待挪车");
                return Result.OK("开柜成功！使用后请及时关闭！");
            }
            assert result != null;
            return Result.Error( "开柜失败：" + result.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.Error( "开柜接口调用失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "我要用车（targetPosition）", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", dataType = "int", required = true, value = "车辆接车信息编号"),
            @ApiImplicitParam(paramType = "query", name = "movedPhoto", dataType = "String", required = true, value = "挪车照片URL")
    })
    @PostMapping("/useCar")
    public Result<String> useCar(@RequestParam int id, @RequestParam String targetPosition, @RequestParam String targetTime) {
        carReceptionService.useCar(id, targetPosition, LocalDateTime.parse(targetTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        // websocket通知
        webSocketService.sendMessage("1", "您有新的待还车订单！");
        return Result.OK("用车成功");
    }

    @ApiOperation(value = "取消预约用车）", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", dataType = "int", required = true, value = "车辆接车信息编号"),
            @ApiImplicitParam(paramType = "query", name = "movedPhoto", dataType = "String", required = true, value = "挪车照片URL")
    })
    @PostMapping("/cancelUseCar")
    public Result<String> cancelUseCar(@RequestParam int id) {
        carReceptionService.cancelUseCar(id);
        return Result.OK("取消预约成功!");
    }
}
